<?php

/**
 *  52zll.top
 */

if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}

if(empty($_GET['code'])) {

	dsetcookie("referer_url", $_GET['referer']);
	$scope = 'snsapi_userinfo';

	$redirect_uri = urlencode($_G['siteurl'].'plugin.php?id=dzapp_zhibo&mod=oauth');
	$appid = $config['wx_appid'];
	dheader("Location: https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=$scope#wechat_redirect");

} else {

	$output = httpGet('https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$config['wx_appid'].'&secret='.$config['wx_appsecret'].'&code='.$_GET['code'].'&grant_type=authorization_code');
	$output = json_decode($output, true);
	$openid = $output['openid'];
	if(empty($openid)) {
		showmessage('dzapp_account:openid_fail');
	}

	$user = C::t('#dzapp_zhibo#dzapp_zhibo_user')->fetch_by_openid_appid($openid, $config['wx_appid']);
	if(empty($user)) {
		$user['id'] = C::t('#dzapp_zhibo#dzapp_zhibo_user')->insert(array('openid' => $openid, 'appid' => $config['wx_appid'], 'firsttime' => $_G['timestamp'], 'updatetime' => $_G['timestamp'], 'method' => 'oauth', 'device' => $_G['mobile']), true);
	}
	
	$member = C::t('common_member')->fetch($user['uid']);
	
	if($user['uid'] && $member['uid']){
		require_once libfile('function/member');
		$member = getuserbyuid($user['uid'], 1);
		setloginstatus($member, 1296000);
	} else {
		$user_info = httpGet('https://api.weixin.qq.com/sns/userinfo?access_token='.$output['access_token'].'&openid='.$openid.'&lang=zh_CN');
		$user_info = json_decode($user_info, true);
		$nickname = diconv($user_info['nickname'], 'UTF-8', CHARSET);
		loaducenter();
		$username = getnewname($user_info['nickname']);
		$exsit = uc_get_user($username);
		
		$username = $exsit ? cutstr($username, 10, '').'_'.random(4) : $username;
		$uid = register($username, $var['group']);
		syncAvatar($uid, $user_info['headimgurl']);
		C::t('#dzapp_zhibo#dzapp_zhibo_user')->update($user['id'], array('uid' => $_G['uid'], 'username' => $_G['username'], 'nickname' => $nickname, 'headimgurl' => $user_info['headimgurl'], 'method' => 'autoreg', 'device' => $_G['mobile']));
	}

	dheader("Location:".str_replace('&amp;', '&', $_G['cookie']['referer_url']));
}
//From:www_caogen8_co
?>